#!/bin/sh
#convert a .tar.gz file to .pet...
#passed param is file to be converted.
#this works for md5sum returning 8-bit characters!

TARBALL=$1
[ ! -f "${TARBALL}" ] && exit 1
chmod 644 ${TARBALL} #make it writable.

# only accept .tgz .tar.gz .txz tar.xz files...
EXT=''
case ${TARBALL} in
  *.tar.gz) EXT='.tar.gz' ;;
  *.tgz)    EXT='.tgz' ;;
  *.tar.xz) EXT='.tar.xz' ;;
  *.txz)    EXT='.txz' ;;
  *) echo "${1##*/}: File extension not allowed" >&2 ; exit 1 ;;
esac

# split TARBALL path/filename into components...
BASEPKG="`basename ${TARBALL} $EXT`"
DIRPKG="`dirname ${TARBALL}`"
[ "${DIRPKG}" = "/" ] && DIRPKG=""

case $EXT in 	
 *gz) OPT=-z ;; 	
 *xz) OPT=-J ;; 	
esac 	
 	
case $EXT in 	
 *tgz) 	
 mv -f ${TARBALL} ${DIRPKG}/${BASEPKG}.tar.gz
 TARBALL="${DIRPKG}/${BASEPKG}.tar.gz"
 EXT='.tar.gz' 	
 ;; 	
 *txz) 	
 mv -f ${TARBALL} ${DIRPKG}/${BASEPKG}.tar.xz
 TARBALL="${DIRPKG}/${BASEPKG}.tar.xz"
 EXT='.tar.xz' 	
 ;; 	
esac

# if tarball expands direct to '/' want to wrap around it (slackware pkg)... 100628 add -z ...
# man bad bug here... the thing isn't expanded! #131122
if [ "`tar ${OPT} --list -f ${TARBALL} | head -n 1`" = "./" ];then
  [ -d ${DIRPKG}/${BASEPKG} ] && exit 1
  mkdir ${DIRPKG}/${BASEPKG}
  mv ${TARBALL} ${DIRPKG}/${BASEPKG}/
  ( cd ${DIRPKG}/${BASEPKG}/ ; tar xf ${TARBALL} ; rm ${TARBALL} )
  tar --remove-files -c -f ${DIRPKG}/${BASEPKG}.tar ${DIRPKG}/${BASEPKG}/
  case $EXT in
    *gz) gzip --best ${DIRPKG}/${BASEPKG}.tar ;;
    *xz) xz -z -9 -e ${DIRPKG}/${BASEPKG}.tar ;;
  esac
fi

echo -n `md5sum ${TARBALL} | cut -f 1 -d ' '` >> ${TARBALL}
mv -f ${TARBALL} ${DIRPKG}/${BASEPKG}.pet
sync

### END ###
